from oauth.models import *
from api.serializers.permissions import *
from rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin, DestroyModelMixin,UpdateModelMixin
from rest_framework.generics import GenericAPIView
from rest_framework.viewsets import ModelViewSet
from utils.Mixins import  MultipleDestroyMixin
from utils.views import  TreeAPIView

from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework_jwt.authentication import JSONWebTokenAuthentication  # jwt用户认证

from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import get_user_model
Users = get_user_model()

from utils.custom_log   import log_start
logger = log_start('django')


class PermissionsViewSet(TreeAPIView,ModelViewSet,MultipleDestroyMixin):
    """
    create:
    权限--新增

    权限新增, status: 201(成功), return: 新增权限信息

    destroy:
    权限--删除

    权限删除, status: 204(成功), return: None

    multiple_delete:
    权限--批量删除

    权限批量删除, status: 204(成功), return: None

    update:
    权限--修改

    权限修改, status: 200(成功), return: 修改增权限信息

    partial_update:
    权限--局部修改

    权限局部修改, status: 200(成功), return: 修改增权限信息

    list:
    权限--获取列表

    权限列表信息, status: 200(成功), return: 权限信息列表
    """
    queryset = Permissions.objects.all()
    serializer_class = PermissionsSerializer
    filter_backends = (SearchFilter, OrderingFilter)
    search_fields = ['name', 'desc', 'path']
    ordering_fields = ['id', 'name']
    
    def get_serializer_class(self):
        if self.action == 'list':
            return PermissionsTreeSerializer
        else:
            return PermissionsSerializer

class PermissionsMethodsAPIView(APIView):
    """
    get:
    权限方法列表
    
    权限models中的方法列表信息, status: 200(成功), return: 权限models中的方法列表
    """
    def get(self, request):
        choices = Permissions.method_choices
        methods =  [{'value':x, 'label':y}  for x,y in choices]
        return Response(data={'results': methods})



class PermissionsAPIView(APIView):
    """
    get:
    获取用户拥有权限ID列表

    获取用户拥有权限ID列表, status: 200(成功), return: 用户拥有权限ID列表
    """
    def get(self, request, pk):
        try:
            user = Users.objects.get(id=pk)
        except Users.DoesNotExist:
            raise ValidationError('无效的用户ID')
        # admin角色
        if 'admin' in user.roles.values_list('name', flat=True) or user.is_superuser:
            return Response(data={'results': Permissions.objects.values_list('id', flat=True)})
        # 其他角色
        return Response(data={'results': list(filter(None, set(user.roles.values_list('permissions__id', flat=True))))})

